package cn.stylefeng.guns.modular.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.modular.entity.Frame;
import cn.stylefeng.guns.modular.entity.Frameitem;
import cn.stylefeng.guns.modular.entity.Schedule;
import cn.stylefeng.guns.modular.entity.Scheduleitem;
import cn.stylefeng.guns.modular.model.ScheduleCopyDto;
import cn.stylefeng.guns.modular.service.*;
import cn.stylefeng.guns.modular.warpper.FrameWrapper;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *分享菜单界面控制器
 *
 * @author third_e
 * @create 2020/1/2 0002-下午 3:59
 */
@Controller
@RequestMapping("/share")
public class ShareFrameAndScheduleController extends BaseController {

    private static String PREFIX = "/share_frame_schedule";

    @Autowired
    private ShareFrameAndScheduleService shareFrameAndScheduleService;
    @Autowired
    private FrameService frameService;
    @Autowired
    private FrameitemService frameitemService;
    @Autowired
    private ScheduleIndexService scheduleIndexService;
    @Autowired
    private ScheduleitemService scheduleitemService;


    /**
     * 跳转到共享框架界面
     */
    @RequestMapping("/share_frame")
    public String shareFramehtml(){
        return this.PREFIX + "/share_frame.html";
    }

    /**
     * 跳转到共享日程界面
     */
    @RequestMapping("/share_schedule")
    public String shareSchedulehtml(){
        return this.PREFIX + "/share_schedule.html";
    }


    /**
     * 跳转到添加共享框架界面
     * @param frameId：框架id
     * @return
     */
    @RequestMapping("/share_frame_add")
    public String shareFrameAddhtml(Long frameId){
        return this.PREFIX + "/share_frame_add.html";
    }


    /**
     *
     * 跳转到添加共享日程界面
     * @param scheduleId：日程id
     * @return
     */
    @RequestMapping("/share_schedule_add")
    public String shareScheduleAddhtml(Long scheduleId){
        if (ToolUtil.isEmpty(scheduleId)) {
            return this.PREFIX + "/share_schedule_add.html";
        }
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        Schedule theschedule = this.scheduleIndexService.getById(scheduleId);
        if (user.getId().equals(theschedule.getUserId())){
            return "schedule/schedule_edit.html";
        }else {
            return this.PREFIX + "/share_schedule_add.html";
        }
    }

    /**
     * 跳转到查看日程详情界面
     * @param scheduleId：日程id
     * @return
     */
    @RequestMapping("/share_schedule_view")
    public String shareScheduleDetailshtml(Long scheduleId){
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        Schedule theschedule = this.scheduleIndexService.getById(scheduleId);
        if (user.getId().equals(theschedule.getUserId())){
            return this.PREFIX + "/share_schedule_details_myself.html";
        }else {
            return this.PREFIX + "/share_schedule_details.html";
        }
    }

    /**
     * 跳转到查看共享框架界面
     * @param frameId：框架id
     * @return
     */
    @RequestMapping("/share_frame_view")
    public String shareFrameViewhtml(Long frameId){
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        Frame theframe = this.frameService.getById(frameId);
        if (user.getId().equals(theframe.getUserId())){
            return this.PREFIX + "/share_frame_view_myself.html";
        }else {
            return this.PREFIX + "/share_frame_view.html";
        }
    }

    /**
     * 跳转到合并日程界面
     */
    @RequestMapping("/share_schedule_copy")
    public String shareScheduleCopy(){
        return this.PREFIX+"/share_schedule_copy.html";
    }

    /**
     * 获取共享框架
     * @return
     */
    @RequestMapping("/getShareFrame")
    @ResponseBody
    public Object  getShareFrame(@RequestParam(value = "nameOrcontent", required = false) String nameOrcontent,
                                 @RequestParam(value = "otherOrmyself", required = false) String otherOrmyself){
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        Page<Map<String, Object>> frames = this.shareFrameAndScheduleService.getShareFrameInfo(otherOrmyself, nameOrcontent, user.getId());
        Page<Map<String, Object>> wrap = new FrameWrapper(frames).wrap();
        return LayuiPageFactory.createPageInfo(wrap) ;
    }

    /**
     * 获取共享日程
     * @return
     */
    @RequestMapping("/getShareSchedule")
    @ResponseBody
    public Object  getShareSchedule(@RequestParam(value = "nameOrcontent", required = false) String nameOrcontent,
                                    @RequestParam(value = "otherOrmyself", required = false) String otherOrmyself,
                                    @RequestParam(value = "timeLimit", required = false) String timeLimit){

        //拼接查询条件
        String beginTime = "";
        String endTime = "";
        if (ToolUtil.isNotEmpty(timeLimit)) {
            String[] split = timeLimit.split(" - ");
            beginTime = split[0];
            endTime = split[1];
        }

        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        Page<Map<String, Object>> schedules = this.shareFrameAndScheduleService.getShareScheduleInfo(otherOrmyself, nameOrcontent, beginTime, endTime, user.getId());
        Page<Map<String, Object>> wrap = new FrameWrapper(schedules).wrap();
        return LayuiPageFactory.createPageInfo(wrap) ;
    }




    /**
     * 获取他人公开的框架
     * @return
     */
    @RequestMapping("/getOtherFrame")
    @ResponseBody
    public ResponseData getOtherFrame(){
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        Collection<Frame> frames = this.shareFrameAndScheduleService.getOtherFrameInfo(user.getId());
        return ResponseData.success(frames);
    }

    /**
     * 获取他人公开的日程
     * @return
     */
    @RequestMapping("/getOtherSchedule")
    @ResponseBody
    public ResponseData getOtherSchedule(){
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        Collection<Schedule> schedules = this.shareFrameAndScheduleService.getOtherScheduleInfo(user.getId());
        return ResponseData.success(schedules);
    }

    /**
     * 判断当前用户是否存在该框架
     * @param frameId
     * @return
     */
    @RequestMapping("isHasFrame")
    @ResponseBody
    public ResponseData isHasFrame(Long frameId){
        //判断请求是否有误
        if (ToolUtil.isEmpty(frameId)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        Frame theframe = this.frameService.getById(frameId);
        if (theframe.getUserId().equals(user.getId())){
            return ResponseData.error(401,"已存在该框架");
        }else {
            return ResponseData.success("请求成功");
        }

    }


    /**
     * 克隆日程框架
     * @param frame
     * @return
     */
    @RequestMapping("addMyselfFrame")
    @ResponseBody
    public ResponseData addMyselfFrame(Frame frame){
        //判断请求是否有误
        if (ToolUtil.isEmpty(frame.getFrameId())){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }

        LoginUser user =  LoginContextHolder.getContext().getUser(); //获取当前登录的用户
        Frame theframe = this.frameService.getById(frame.getFrameId());//获取当前框架
        //判断当前用户是否存在该日程框架
        if (theframe.getUserId().equals(user.getId())){
            throw new ServiceException(BizExceptionEnum.HAS_SAME_FRAME);
        }else {
            Collection<Frameitem> theframeitems = this.frameitemService.selectFramitem(frame.getFrameId());//获取当前框架项
            //补充字段内容
            frame.setFrameId(null);
            frame.setUserId(user.getId());
            frame.setPostStatus(theframe.getPostStatus());
            this.frameService.save(frame);
            //克隆框架项内容信息
            for(Frameitem frameitem : theframeitems) {
                frameitem.setFrameitemId(null);
                frameitem.setFrameId(frame.getFrameId());
                frameitem.setCreateUser(user.getId());
                this.frameitemService.save(frameitem);
            }
            return SUCCESS_TIP;
        }
    }

    /**
     * 克隆日程
     * @param schedule
     * @return
     */
    @RequestMapping("/addMyselfSchedule")
    @ResponseBody
    public ResponseData addMyselfSchedule(Schedule schedule){
        LoginUser user =  LoginContextHolder.getContext().getUser(); //获取当前登录的用户
        Schedule theoldschedule1 = this.scheduleIndexService.getById(schedule.getScheduleId()); //获取当前选择的日程
        //判断当前用户是否存在该日程框架
        if (user.getId().equals(theoldschedule1.getUserId())){
            throw new ServiceException(BizExceptionEnum.HAS_SAME_FRAME);
        }else {
            //补充克隆日程信息字段
            schedule.setScheduleId(null);
            schedule.setUserId(user.getId());
            schedule.setFrameId(theoldschedule1.getFrameId());
            this.scheduleIndexService.addSchedule(schedule);
            System.out.println("\n\n\n==========================");
            System.out.println("============="+schedule.getScheduleId());
            Collection<Scheduleitem> scheduleitems = this.shareFrameAndScheduleService.getShareScheduleitemInfo(theoldschedule1.getScheduleId(),schedule.getStartData(),schedule.getEndData());
            for (Scheduleitem scheduleitem:scheduleitems){
                scheduleitem.setScheduleitemId(null);
                scheduleitem.setScheduleId(schedule.getScheduleId());
                System.out.println("\n\n\n11111============="+schedule.getScheduleId());
                this.scheduleitemService.save(scheduleitem);
            }
            System.out.println("==========================");
        }
        return SUCCESS_TIP;
    }


    /**
     * 获取日程和框架项信息
     * @param scheduleId
     * @return
     */
    @RequestMapping("/share_getScheduleAndFrameitem")
    @ResponseBody
    public ResponseData getScheduleAndFrameitem(Long scheduleId){
        Schedule schedule = this.shareFrameAndScheduleService.getScheduleAndFrameitem(scheduleId);
        return ResponseData.success(schedule);
    }

    /**
     * 合并日程
     * @param scheduleCopyDto
     * @return
     */
    @RequestMapping("/copySchedule")
    @ResponseBody
    public ResponseData copySchedule(ScheduleCopyDto scheduleCopyDto){
        //获取合并日程
        Collection<Schedule> copySchedules=new ArrayList<>();
        LoginUser user =  LoginContextHolder.getContext().getUser(); //获取当前登录的用户
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//时间判断
        try {
            if (sdf.parse(scheduleCopyDto.getStartData()).getTime()>sdf.parse(scheduleCopyDto.getEndData()).getTime()){
                throw new ServiceException(BizExceptionEnum.TIME_EEROR);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //获取合并自己的日程
        if (!ToolUtil.isEmpty( scheduleCopyDto.getMySchedule())){
            String [] temp = scheduleCopyDto.getMySchedule().split(",");
            for(String a:temp){
                copySchedules.add( this.scheduleIndexService.getOnescheduleInfo(Long.valueOf(a)));
            }
        }
        //获取合并他人的日程
        if (!ToolUtil.isEmpty( scheduleCopyDto.getOtherSchedule())){
            String [] temp = scheduleCopyDto.getOtherSchedule().split(",");
            for(String a:temp){
                copySchedules.add( this.scheduleIndexService.getOnescheduleInfo(Long.valueOf(a)));
            }
        }
        Set<Long> set = new HashSet<>();
        Set<Schedule> scheduleFrameDiff = new HashSet<>(); //不同框架日程
        // 获取查询出来的日程
        for (Schedule schedule:copySchedules){
            if (!set.contains(schedule.getFrameId())) {
                set.add(schedule.getFrameId());
                scheduleFrameDiff.add(schedule);
            }
        }


        if (scheduleFrameDiff.size()<2){//表示属于相同框架的日程
            System.out.println("日程框架相同");

            //获取框架的id
            Long frameId = null;
            Collection<Scheduleitem> allScheduleitem = new ArrayList<>();//获取全部的日程项信息
            for (Schedule schedule:copySchedules){ //遍历全部日程，获取全部日程项
                frameId = schedule.getFrameId();
                Collection<Scheduleitem> scheduleitems = this.scheduleitemService.selectByscheduleId(schedule.getScheduleId());
                for (Scheduleitem scheduleitem:scheduleitems){
                    allScheduleitem.add(scheduleitem);
                }
            }

            //测试
            Set<String> set1 = new HashSet<>();
            Set<Scheduleitem> scheduleitemDiff = new HashSet<>(); //获取冲突的日程项
            Set<Scheduleitem> scheduleitemNot = new HashSet<>(); //获取没有冲突的日程项
            // 获取查询出来的日程
            for (Scheduleitem schedule:allScheduleitem){
                try {
                    if (sdf.parse(schedule.getScheduleitemDay()).getTime() >= sdf.parse(scheduleCopyDto.getStartData()).getTime() &&
                            sdf.parse(schedule.getScheduleitemDay()).getTime() <= sdf.parse(scheduleCopyDto.getEndData()).getTime()){
                        if (!set1.contains(schedule.getScheduleitemDay()+schedule.getStartTime())) {
                            set1.add(schedule.getScheduleitemDay()+schedule.getStartTime());
                            scheduleitemNot.add(schedule);
                        }else {
                            for (Scheduleitem schedule1:allScheduleitem){
                                if (schedule1.getScheduleitemDay().equals(schedule.getScheduleitemDay()) && schedule1.getStartTime().equals(schedule.getStartTime())){
                                    scheduleitemNot.remove(schedule1);
                                    scheduleitemDiff.add(schedule1);
                                }
                            }
                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            //获取冲突日程对应时间
            Map<String, List<Scheduleitem>> stringScheduleitemMap = new HashMap<>();
            for (Scheduleitem scheduleitem:scheduleitemDiff){
                List<Scheduleitem> list = new ArrayList<>();
                if (stringScheduleitemMap.get(scheduleitem.getScheduleitemDay())==null){
                    list.add(scheduleitem);
                    stringScheduleitemMap.put(scheduleitem.getScheduleitemDay(),list);
                }else {
                    stringScheduleitemMap.get(scheduleitem.getScheduleitemDay()).add(scheduleitem);
                    stringScheduleitemMap.put(scheduleitem.getScheduleitemDay(), stringScheduleitemMap.get(scheduleitem.getScheduleitemDay()));
                }
//                System.out.println(stringScheduleitemMap.get(scheduleitem.getScheduleitemDay()));
//                stringScheduleitemMap.put(scheduleitem.getScheduleitemDay(),scheduleitem);
            }
            System.out.println("set1"+stringScheduleitemMap);
//            for (Map.Entry entry : stringScheduleitemMap.entrySet()){
//                System.out.println(entry.getKey());
//                System.out.println(entry.getValue());
//            }
//            System.out.println("set1");
//            for (String scheduleitem:set1){
//                System.out.println(scheduleitem);
//            }
//            System.out.println("获取冲突的日程项");
//            for (Scheduleitem scheduleitem:scheduleitemDiff){
//                System.out.println(scheduleitem);
//            }
//            System.out.println("获取没有冲突的日程项");
//            for (Scheduleitem scheduleitem:scheduleitemNot){
//                System.out.println(scheduleitem);
//            }

            //创建新的日程，并存储没有冲突的日程项
            Schedule newSchedule = new Schedule();
            newSchedule.setScheduleName(scheduleCopyDto.getScheduleName());
            newSchedule.setStartData(scheduleCopyDto.getStartData());
            newSchedule.setEndData(scheduleCopyDto.getEndData());
            newSchedule.setPublicStatus(scheduleCopyDto.getPublicStatus());
            newSchedule.setDescription(scheduleCopyDto.getDescription());
            newSchedule.setFrameId(frameId);
            newSchedule.setUserId(user.getId());
            this.scheduleIndexService.save(newSchedule);
            Map<String, Object> resData = new HashMap<>();
            resData.put("scheduleId",newSchedule.getScheduleId());
//            resData.put("scheduleId",11111111);
            resData.put("scheduleitem",stringScheduleitemMap);
            //存储日程项
            for (Scheduleitem scheduleitem:scheduleitemNot){
                scheduleitem.setScheduleitemId(null);
                scheduleitem.setScheduleId(newSchedule.getScheduleId());
                this.scheduleitemService.save(scheduleitem);

            }

            if (!ToolUtil.isEmpty(scheduleitemDiff)){
                System.out.println("aaaaa");
                return ResponseData.error(400,"合成失败",resData);
            }else {
                System.out.println("bbbbb");
                return SUCCESS_TIP;
            }



            //通过日期、日程、框架项判断；判断日期相同，不同日程，相同框架项：表示有行程冲突
//            String message ="日程中";
//            for (int i=0;i<allScheduleitem.size();i++){
//                for (int a =i;a<allScheduleitem.size();a++){
//                    if (((ArrayList<Scheduleitem>) allScheduleitem).get(i).getScheduleitemDay().equals(((ArrayList<Scheduleitem>) allScheduleitem).get(a).getScheduleitemDay()) &&
//                            ((ArrayList<Scheduleitem>) allScheduleitem).get(i).getScheduleId() !=((ArrayList<Scheduleitem>) allScheduleitem).get(a).getScheduleId() &&
//                            ((ArrayList<Scheduleitem>) allScheduleitem).get(i).getFrameitemId() ==((ArrayList<Scheduleitem>) allScheduleitem).get(a).getFrameitemId() ){
//                        System.out.println(((ArrayList<Scheduleitem>) allScheduleitem).get(i).getScheduleitemDay()+"\t"+((ArrayList<Scheduleitem>) allScheduleitem).get(i).getScheduleId()+"\t"+((ArrayList<Scheduleitem>) allScheduleitem).get(i).getFrameitemId());
//
//                        System.out.println(((ArrayList<Scheduleitem>) allScheduleitem).get(a).getScheduleitemDay()+"\t"+((ArrayList<Scheduleitem>) allScheduleitem).get(a).getScheduleId()+"\t"+((ArrayList<Scheduleitem>) allScheduleitem).get(a).getFrameitemId());
//                        System.out.println(((ArrayList<Scheduleitem>) allScheduleitem).get(a));
//                         message += ((ArrayList<Scheduleitem>) allScheduleitem).get(a).getScheduleitemDay()+"中，时间段"+((ArrayList<Scheduleitem>) allScheduleitem).get(a).getStartTime()+"-"+((ArrayList<Scheduleitem>) allScheduleitem).get(a).getEndTime();
////                        return ResponseData.error(400,"合成失败",message+"有行程冲突");
//                    }else {
//                        System.out.println(i+"这是i"+((ArrayList<Scheduleitem>) allScheduleitem).get(a));
//                    }
//                }
//            }

            //没有冲突则先存储日程
//            Schedule newSchedule = new Schedule();
//            newSchedule.setScheduleName(scheduleCopyDto.getScheduleName());
//            newSchedule.setStartData(scheduleCopyDto.getStartData());
//            newSchedule.setEndData(scheduleCopyDto.getEndData());
//            newSchedule.setPublicStatus(scheduleCopyDto.getPublicStatus());
//            newSchedule.setDescription(scheduleCopyDto.getDescription());
//            newSchedule.setFrameId(frameId);
//            newSchedule.setUserId(user.getId());
//            this.scheduleIndexService.save(newSchedule);
            //存储日程项

//            try {
//                for (Scheduleitem scheduleitem:allScheduleitem){
//                        if (sdf.parse(scheduleitem.getScheduleitemDay()).getTime() >= sdf.parse(scheduleCopyDto.getStartData()).getTime() &&
//                                sdf.parse(scheduleitem.getScheduleitemDay()).getTime() <= sdf.parse(scheduleCopyDto.getEndData()).getTime()){
//                            scheduleitem.setScheduleitemId(null);
//                            scheduleitem.setScheduleId(newSchedule.getScheduleId());
//                                this.scheduleitemService.save(scheduleitem);
//                        }
//                }
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//            System.out.println("================");
//            return SUCCESS_TIP;
        }else {
            //不同日程框架，不能合成
            String message = "所选：";
            for (Schedule schedule:scheduleFrameDiff){
                message+="日程"+schedule.getScheduleName()+" ";
            }
            message +="日程之间的框架不相同";
            return ResponseData.error(400,"合成失败",message);
        }



    }

    @RequestMapping("/test1")
    @ResponseBody
    public ResponseData test1(ScheduleCopyDto scheduleCopyDto){
        LoginUser user =  LoginContextHolder.getContext().getUser(); //获取当前登录的用户
        System.out.println("\n\n==================="+scheduleCopyDto);
        if (ToolUtil.isEmpty(scheduleCopyDto.getScheduleId())){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        if (!ToolUtil.isEmpty(scheduleCopyDto.getScheduleitemId())){
            for (Long id:scheduleCopyDto.getScheduleitemId()){
                Scheduleitem scheduleitem = this.scheduleitemService.getById(id);
                scheduleitem.setScheduleitemId(null);
                scheduleitem.setCreateUser(user.getId());
                scheduleitem.setScheduleId(scheduleCopyDto.getScheduleId());
                this.scheduleitemService.save(scheduleitem);
            }
        }
        return SUCCESS_TIP;
    }
}
